<template>
	<div>
		<el-input v-model="visidId"></el-input>
		<el-button @click="getMedicalReport()">查询</el-button>
	</div>
</template>

<script>
	import http from "@/utils/request";
	export default {
		data() {
			return {
				tableData: [],
				visidId: ''
			}
		},
		methods: {
			async getMedicalReport() {
				const resp = await http.get('/doctor/getMedicalReport', {
					headers: {
						doctorId: this.$store.state.user.id,
						visitId: this.visidId
					}
				})
				this.tableData = resp.data.data
				console.log(this.tableData)
			}
		}
	}
</script>

<style>
</style><template>
	<div class="medical-report-container">
		<!-- 查询区域 -->
		<div class="search-section">
			<el-card class="search-card">
				<div class="search-form">
					<el-input placeholder="请输入患者诊疗号" v-model="visitId" clearable
						style="width: 300px; margin-right: 15px;">
						<template slot="prepend">诊疗号</template>
					</el-input>
					<el-button type="primary" @click="getMedicalReport()" :loading="loading" icon="el-icon-search">
						查询
					</el-button>
				</div>
			</el-card>
		</div>

		<!-- 检查报告列表区域 -->
		<div class="report-list-section" v-if="tableData.length > 0">
			<el-row :gutter="20">
				<el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6" v-for="report in tableData" :key="report.reportId"
					style="margin-bottom: 20px;">
					<el-card class="report-card" shadow="hover">
						<!-- 报告卡片头部 -->
						<div slot="header" class="card-header">
							<span class="report-title">{{ formatReportType(report.reportType) }}</span>
							<el-tag :type="getEmpowerTagType(report.isEmpower)" size="small">
								{{ report.isEmpower }}
							</el-tag>
						</div>

						<!-- 报告基本信息 -->
						<div class="report-info">
							<div class="info-item">
								<i class="el-icon-document"></i>
								<span class="label">报告ID：</span>
								<span class="value">{{ report.reportId }}</span>
							</div>
							<div class="info-item">
								<i class="el-icon-date"></i>
								<span class="label">创建时间：</span>
								<span class="value">{{ formatDate(report.createdTime) }}</span>
							</div>
							<div class="info-item" v-if="report.hospitalName">
								<i class="el-icon-office-building"></i>
								<span class="label">医院：</span>
								<span class="value">{{ report.hospitalName }}</span>
							</div>
							<!-- 影像报告显示预览图 -->
							<div v-if="report.reportType === 'imaging' && report.medicalReportInfo?.ossUrl"
								class="image-preview">
								<div class="preview-label">
									<i class="el-icon-picture"></i>
									<span>影像预览：</span>
								</div>
								<div class="preview-image" @click="showImageDetail(report)">
									<img :src="report.medicalReportInfo.ossUrl" alt="影像图片" class="image-thumbnail" />
									<div class="image-overlay">
										<i class="el-icon-zoom-in"></i>
									</div>
								</div>
							</div>
						</div>

						<!-- 操作按钮区域 -->
						<div class="action-buttons">
							<!-- 未授权状态：发送授权请求 -->
							<el-button v-if="report.isEmpower === '未授权'" type="primary" size="small"
								@click="requestMedicalReportEmpower(report)" :loading="report.requestLoading" plain
								icon="el-icon-connection">
								请求授权
							</el-button>

							<!-- 授权中状态：显示等待 -->
							<el-button v-if="report.isEmpower === '授权中'" type="info" size="small" disabled
								icon="el-icon-time">
								授权审核中
							</el-button>

							<!-- 已拒绝：显示拒绝 -->
							<el-button v-if="report.isEmpower === '已拒绝'" type="danger" size="small">
								请求授权
							</el-button>

							<!-- 已授权状态：查看详情 -->
							<el-button v-if="report.isEmpower === '已授权'" type="success" size="small"
								@click="showReportDetail(report)" icon="el-icon-view">
								查看详情
							</el-button>
						</div>
					</el-card>
				</el-col>
			</el-row>
		</div>

		<!-- 空状态 -->
		<div class="empty-state" v-else-if="!loading && hasSearched">
			<el-empty description="暂无检查报告" :image-size="200">
				<div slot="image">
					<i class="el-icon-document-delete" style="font-size: 100px; color: #c0c4cc;"></i>
				</div>
			</el-empty>
		</div>

		<!-- 报告详情抽屉 -->
		<el-drawer :visible.sync="drawerVisible" title="检查报告详情" size="60%" :close-on-click-modal="false">
			<div class="report-detail" v-if="currentReport">
				<!-- 报告基本信息 -->
				<el-descriptions title="报告基本信息" :column="2" border>
					<el-descriptions-item label="报告ID">
						{{ currentReport.reportId || '暂无' }}
					</el-descriptions-item>
					<el-descriptions-item label="报告类型">
						{{ formatReportType(currentReport.reportType) || '暂无' }}
					</el-descriptions-item>
					<el-descriptions-item label="诊疗号">
						{{ currentReport.visitId || '暂无' }}
					</el-descriptions-item>
					<el-descriptions-item label="创建时间">
						{{ formatDate(currentReport.createdTime) || '暂无' }}
					</el-descriptions-item>
				</el-descriptions>

				<!-- 详细报告内容 -->
				<div class="report-content" v-if="currentReport.medicalReportInfo">
					<el-tabs type="border-card">
						<!-- 报告详情 -->
						<el-tab-pane label="报告详情">
							<div class="content-box">
								<el-row :gutter="20">
									<el-col :span="12" v-if="currentReport.medicalReportInfo.reportName">
										<div class="detail-item">
											<span class="detail-label">报告名称：</span>
											<span
												class="detail-value">{{ currentReport.medicalReportInfo.reportName }}</span>
										</div>
									</el-col>
									<el-col :span="12" v-if="currentReport.medicalReportInfo.itemCode">
										<div class="detail-item">
											<span class="detail-label">项目代码：</span>
											<span
												class="detail-value">{{ currentReport.medicalReportInfo.itemCode }}</span>
										</div>
									</el-col>
									<el-col :span="24" v-if="currentReport.medicalReportInfo.resultItems">
										<div class="detail-item">
											<span class="detail-label">结果项目：</span>
											<div class="result-items-container">
												<!-- 解析JSON格式的结果项目 -->
												<div v-if="isJsonString(currentReport.medicalReportInfo.resultItems)"
													class="json-result-items">
													<div v-for="(value, key) in parseJson(currentReport.medicalReportInfo.resultItems)"
														:key="key" class="json-item">
														<span class="json-key">{{ key }}：</span>
														<span class="json-value">{{ value }}</span>
													</div>
												</div>
												<!-- 非JSON格式的结果项目 -->
												<span v-else
													class="detail-value">{{ currentReport.medicalReportInfo.resultItems }}</span>
											</div>
										</div>
									</el-col>
									<el-col :span="24" v-if="currentReport.medicalReportInfo.conclusion">
										<div class="detail-item">
											<span class="detail-label">检查结论：</span>
											<div class="conclusion-box">{{ currentReport.medicalReportInfo.conclusion }}
											</div>
										</div>
									</el-col>
									<el-col :span="12" v-if="currentReport.medicalReportInfo.reporterName">
										<div class="detail-item">
											<span class="detail-label">报告医生：</span>
											<span
												class="detail-value">{{ currentReport.medicalReportInfo.reporterName }}</span>
										</div>
									</el-col>
									<el-col :span="12" v-if="currentReport.medicalReportInfo.reportTime">
										<div class="detail-item">
											<span class="detail-label">报告时间：</span>
											<span
												class="detail-value">{{ formatDate(currentReport.medicalReportInfo.reportTime) }}</span>
										</div>
									</el-col>
									<el-col :span="12" v-if="currentReport.medicalReportInfo.verifyDoctorName">
										<div class="detail-item">
											<span class="detail-label">审核医生：</span>
											<span
												class="detail-value">{{ currentReport.medicalReportInfo.verifyDoctorName }}</span>
										</div>
									</el-col>
									<el-col :span="12" v-if="currentReport.medicalReportInfo.verifyTime">
										<div class="detail-item">
											<span class="detail-label">审核时间：</span>
											<span
												class="detail-value">{{ formatDate(currentReport.medicalReportInfo.verifyTime) }}</span>
										</div>
									</el-col>
								</el-row>
							</div>
						</el-tab-pane>

						<!-- 影像查看（仅影像报告显示） -->
						<el-tab-pane v-if="currentReport.reportType === 'imaging'" label="影像查看">
							<div class="image-viewer">
								<template v-if="currentReport.medicalReportInfo.ossUrl">
									<div class="image-container">
										<img :src="currentReport.medicalReportInfo.ossUrl" alt="检查影像"
											class="viewer-image" />
									</div>
									<div class="image-tools">
										<el-button type="primary" size="small"
											@click="downloadImage(currentReport.medicalReportInfo.ossUrl)">
											<i class="el-icon-download"></i> 下载图片
										</el-button>
										<el-button type="info" size="small"
											@click="openImageInNewTab(currentReport.medicalReportInfo.ossUrl)">
											<i class="el-icon-full-screen"></i> 新窗口打开
										</el-button>
									</div>
								</template>
								<div v-else class="no-image">
									<el-empty description="暂无影像图片" />
								</div>
							</div>
						</el-tab-pane>
					</el-tabs>
				</div>

				<!-- 无详细信息的提示 -->
				<div v-else class="no-detail">
					<el-empty description="暂无详细报告信息" />
				</div>
			</div>
		</el-drawer>
	</div>
</template>

<script>
	import http from "@/utils/request";

	export default {
		name: 'MedicalReportList',
		data() {
			return {
				visitId: '',
				tableData: [],
				loading: false,
				drawerVisible: false,
				currentReport: null,
				hasSearched: false // 标记是否已进行过搜索
			}
		},
		methods: {
			async getMedicalReport() {
				if (!this.visitId) {
					this.$message.warning('请输入诊疗号');
					return;
				}

				this.loading = true;
				this.hasSearched = true;
				try {
					const resp = await http.get('/doctor/getMedicalReport', {
						headers: {
							visitId: this.visitId,
							doctorId: this.$store.state.user.id
						}
					});

					if (resp.data.code === 1) {
						this.tableData = resp.data.data || [];
						this.$message.success('查询成功');
					} else {
						this.$message.error(resp.data.msg || '查询失败');
					}
				} catch (error) {
					console.error('查询检查报告失败:', error);
					this.$message.error('查询失败，请检查网络连接');
				} finally {
					this.loading = false;
				}
			},

			// 发送授权请求
			async requestMedicalReportEmpower(report) {
				this.$set(report, 'requestLoading', true);
				try {
					const resp = await http.post('/doctor/requestMedicalReportEmpower', {
						reportId: report.reportId,
						doctorId: this.$store.state.user.id,
						visitId: this.visitId
					});

					if (resp.data.code === 1) {
						this.$message.success('授权请求发送成功');
						report.isEmpower = '授权中';
						await this.getMedicalReport();
					} else {
						this.$message.error(resp.data.msg || '发送失败');
					}
				} catch (error) {
					console.error('发送授权请求失败:', error);
					this.$message.error('发送失败');
				} finally {
					this.$set(report, 'requestLoading', false);
				}
			},

			// 查看报告详情
			showReportDetail(report) {
				this.currentReport = report;
				this.drawerVisible = true;
			},

			// 查看图片详情
			showImageDetail(report) {
				this.currentReport = report;
				this.drawerVisible = true;
			},

			// 格式化日期
			formatDate(dateString) {
				if (!dateString) return '暂无';
				return dateString.replace('T', ' ').substring(0, 16);
			},

			// 格式化报告类型
			formatReportType(type) {
				const typeMap = {
					'imaging': '影像报告',
					'lab': '检验报告',
					'pathology': '病理报告'
				};
				return typeMap[type] || type;
			},

			// 根据授权状态获取标签类型
			getEmpowerTagType(status) {
				const typeMap = {
					'未授权': 'info',
					'授权中': 'warning',
					'已授权': 'success',
					'已拒绝': 'danger',
					'未知': 'danger'
				};
				return typeMap[status] || 'info';
			},

			// 下载图片
			downloadImage(url) {
				if (!url) {
					this.$message.warning('暂无图片可下载');
					return;
				}

				const link = document.createElement('a');
				link.href = url;
				link.download = `medical_image_${this.currentReport.reportId}.jpg`;
				document.body.appendChild(link);
				link.click();
				document.body.removeChild(link);
				this.$message.success('图片下载已开始');
			},

			// 新窗口打开图片
			openImageInNewTab(url) {
				if (!url) {
					this.$message.warning('暂无图片可查看');
					return;
				}

				window.open(url, '_blank');
			},

			// 检查字符串是否为JSON格式
			isJsonString(str) {
				if (typeof str !== 'string') {
					return false;
				}
				try {
					JSON.parse(str);
					return true;
				} catch (error) {
					return false;
				}
			},

			// 解析JSON字符串
			parseJson(str) {
				try {
					return JSON.parse(str);
				} catch (error) {
					console.error('JSON解析失败:', error);
					return {};
				}
			}
		}
	}
</script>

<style scoped>
	.medical-report-container {
		padding: 20px;
		background-color: #f5f7fa;
		min-height: calc(100vh - 84px);
	}

	.search-section {
		margin-bottom: 20px;
	}

	.search-card {
		border-radius: 8px;
	}

	.search-form {
		display: flex;
		align-items: center;
	}

	.report-list-section {
		margin-top: 20px;
	}

	.report-card {
		height: 100%;
		transition: transform 0.3s ease;
	}

	.report-card:hover {
		transform: translateY(-5px);
	}

	.card-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 18px 20px;
	}

	.report-title {
		font-size: 16px;
		font-weight: bold;
		color: #409eff;
	}

	.report-info {
		margin-bottom: 20px;
	}

	.info-item {
		display: flex;
		align-items: center;
		margin-bottom: 12px;
		font-size: 13px;
		color: #606266;
	}

	.info-item i {
		margin-right: 8px;
		color: #909399;
	}

	.info-item .label {
		min-width: 70px;
		color: #909399;
	}

	.info-item .value {
		flex: 1;
		color: #303133;
		word-break: break-all;
	}

	/* 影像预览样式 */
	.image-preview {
		margin-top: 15px;
		border-top: 1px solid #ebeef5;
		padding-top: 15px;
	}

	.preview-label {
		display: flex;
		align-items: center;
		margin-bottom: 10px;
		font-size: 13px;
		color: #909399;
	}

	.preview-label i {
		margin-right: 8px;
	}

	.preview-image {
		position: relative;
		width: 100%;
		height: 120px;
		border-radius: 4px;
		overflow: hidden;
		cursor: pointer;
		transition: all 0.3s ease;
	}

	.preview-image:hover {
		transform: scale(1.02);
		box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
	}

	.image-thumbnail {
		width: 100%;
		height: 100%;
		object-fit: cover;
	}

	.image-overlay {
		position: absolute;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background: rgba(0, 0, 0, 0.3);
		display: flex;
		align-items: center;
		justify-content: center;
		opacity: 0;
		transition: opacity 0.3s ease;
	}

	.preview-image:hover .image-overlay {
		opacity: 1;
	}

	.image-overlay i {
		color: white;
		font-size: 24px;
	}

	.action-buttons {
		display: flex;
		justify-content: center;
		gap: 10px;
	}

	.empty-state {
		display: flex;
		justify-content: center;
		align-items: center;
		height: 400px;
	}

	.report-detail {
		padding: 0 20px;
	}

	.report-detail .el-descriptions {
		margin-bottom: 20px;
	}

	.report-content {
		margin-top: 20px;
	}

	.content-box {
		padding: 20px;
		background-color: #f9f9f9;
		border-radius: 4px;
	}

	.detail-item {
		margin-bottom: 15px;
	}

	.detail-label {
		font-weight: bold;
		color: #606266;
		margin-right: 10px;
	}

	.detail-value {
		color: #303133;
	}

	.conclusion-box {
		padding: 15px;
		background-color: white;
		border: 1px solid #e4e7ed;
		border-radius: 4px;
		margin-top: 10px;
		line-height: 1.6;
		white-space: pre-wrap;
		word-wrap: break-word;
	}

	/* 影像查看器样式 */
	.image-viewer {
		padding: 20px;
	}

	.image-container {
		width: 100%;
		max-height: 500px;
		overflow: auto;
		margin-bottom: 20px;
		background-color: #f5f5f5;
		border-radius: 4px;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.viewer-image {
		max-width: 100%;
		max-height: 500px;
		object-fit: contain;
	}

	.image-tools {
		display: flex;
		justify-content: center;
		gap: 15px;
	}

	.no-image {
		text-align: center;
		padding: 40px 0;
	}

	.no-detail {
		text-align: center;
		padding: 40px 0;
	}

	@media (max-width: 768px) {
		.search-form {
			flex-direction: column;
			gap: 10px;
		}

		.search-form .el-input {
			width: 100% !important;
			margin-right: 0 !important;
		}

		.report-detail {
			padding: 0 10px;
		}

		.card-header {
			flex-direction: column;
			align-items: flex-start;
			gap: 10px;
		}

		.image-container {
			max-height: 300px;
		}

		.image-tools {
			flex-direction: column;
		}
	}

	/* JSON结果项目样式 */
	.result-items-container {
		margin-top: 10px;
	}

	.json-result-items {
		background-color: white;
		border: 1px solid #e4e7ed;
		border-radius: 4px;
		padding: 15px;
	}

	.json-item {
		margin-bottom: 10px;
		line-height: 1.6;
	}

	.json-item:last-child {
		margin-bottom: 0;
	}

	.json-key {
		font-weight: bold;
		color: #606266;
		margin-right: 10px;
	}

	.json-value {
		color: #303133;
		word-break: break-word;
	}
</style>